package com.txsj.scan.reader;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.greendao.TagInfoDao;
import com.nativec.tools.ModuleManager;
import com.nativec.tools.SerialPort;
import com.nativec.tools.SerialPortFinder;
import com.txsj.scan.R;
import com.txsj.scan.bean.TagInfo;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.reader.base.ReaderBase;
import com.txsj.scan.reader.helper.InventoryBuffer;
import com.txsj.scan.reader.helper.ReaderHelper;
import com.txsj.scan.reader.helper.ReaderSetting;
import com.txsj.scan.utils.Trace;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;

public class EpcUtils {

    private static EpcUtils instance;
    private static Activity activity;

    private static final String TAG = "COONECTRS232";
    private static final String TTYS1 = "ttyS4 (rk_serial)";     //串口号
    private int baud = 115200;                                      //波特率
    private static final boolean DEBUG = true;

    //连接
    private ReaderHelper mReaderHelper;
    private List<String> mPortList = new ArrayList<String>();       //查到串口后的集合
    private int mPosPort = -1;                                 //当前选择的串口
    private SerialPortFinder mSerialPortFinder;                //串口查找器
    String[] entries = null;                    //串口查到所有设备后返回的数组
    String[] entryValues = null;                //串口查到后设备对应的路径
    public static SerialPort mSerialPort = null;

    //连接后进行读取
    private ReaderBase mReader;
    private static ReaderSetting m_curReaderSetting;
    private static InventoryBuffer m_curInventoryBuffer;
    private LocalBroadcastManager lbm;


    private boolean isStarted = false;//是否已经开始扫描

    public boolean isStarted() {
        return isStarted;
    }

    private EpcUtils(){
        mSerialPortFinder = new SerialPortFinder();
        entries = mSerialPortFinder.getAllDevices();
        entryValues = mSerialPortFinder.getAllDevicesPath();

        String[] lists = entries;
        for(int i = 0; i < lists.length; i++){
            mPortList.add(lists[i]);
        }
    }

    public static EpcUtils getInstance(Activity context){
        if (null == instance){
            instance = new EpcUtils();
        }
        activity = context;
        return instance;
    }

    /**
     * 开始扫描
     */
    public void startStop(){
        initScanParam();

        m_curInventoryBuffer.clearInventoryPar();

        m_curInventoryBuffer.lAntenna.add((byte) 0x00);

        if (m_curInventoryBuffer.lAntenna.size() <= 0) {
            Toast.makeText(activity,
                    activity.getResources().getString(R.string.antenna_empty),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.bLoopInventoryReal = true;
        m_curInventoryBuffer.btRepeat = 0;

        String strRepeat = "1";
        if (strRepeat == null || strRepeat.length() <= 0) {
            Toast.makeText(activity,
                    activity.getResources().getString(R.string.repeat_empty),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.btRepeat = (byte) Integer.parseInt(strRepeat);

        if ((m_curInventoryBuffer.btRepeat & 0xFF) <= 0) {
            Toast.makeText(activity,
                    activity.getResources().getString(R.string.repeat_min),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.bLoopCustomizedSession = false;


        {
            //判断是否已经开始盘存
            if (isStarted) {
                mReaderHelper.setInventoryFlag(false);
                m_curInventoryBuffer.bLoopInventoryReal = false;

                mLoopHandler.removeCallbacks(mLoopRunnable);
                mHandler.removeCallbacks(mRefreshRunnable);

                isStarted = !isStarted;
                Trace.e("已经结束盘存");
                return;
            } else {
                isStarted = !isStarted;
                Trace.e("盘存中。。。");
            }
        }

        mReaderHelper.setInventoryFlag(true);

        mReaderHelper.clearInventoryTotal();

        byte btWorkAntenna = m_curInventoryBuffer.lAntenna
                .get(m_curInventoryBuffer.nIndexAntenna);
        if (btWorkAntenna < 0)
            btWorkAntenna = 0;
        mReaderHelper.runLoopInventroy();
        m_curReaderSetting.btWorkAntenna = btWorkAntenna;

        mLoopHandler.removeCallbacks(mLoopRunnable);
        mLoopHandler.postDelayed(mLoopRunnable, 2000);
        mHandler.removeCallbacks(mRefreshRunnable);
        mHandler.postDelayed(mRefreshRunnable, 2000);
    }


    /**
     * 在Activity用到了本类的时候必须调用此方法
     */
    public void onResume(){
        if (mReader != null) {
            if (!mReader.IsAlive())
                mReader.StartWait();
        }
    }

    private Handler mHandler = new Handler();
    private Runnable mRefreshRunnable = new Runnable() {
        public void run() {
//            refreshList();
            mHandler.postDelayed(this, 2000);
        }
    };
    private Handler mLoopHandler = new Handler();
    private Runnable mLoopRunnable = new Runnable() {
        public void run() {
            /*
             * byte btWorkAntenna =
             * m_curInventoryBuffer.lAntenna.get(m_curInventoryBuffer
             * .nIndexAntenna); if (btWorkAntenna < 0) btWorkAntenna = 0;
             * mReader.setWorkAntenna(m_curReaderSetting.btReadId,
             * btWorkAntenna);
             */
            mReaderHelper.runLoopInventroy();
            mLoopHandler.postDelayed(this, 2000);
//            saveDataToSql();
        }
    };

    /**
     * 将读到的数据放入数据库
     */
    public void saveDataToSql() {
        if (null == m_curInventoryBuffer || null == m_curInventoryBuffer.lsTagList || m_curInventoryBuffer.lsTagList.size() <= 0){
            return;
        }
        TagInfoDao tagInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getTagInfoDao();
        long times = System.currentTimeMillis();
        for (int i = 0; i < m_curInventoryBuffer.lsTagList.size(); i++) {
            InventoryBuffer.InventoryTagMap map = m_curInventoryBuffer.lsTagList.get(i);
            Trace.e("lsTagList:"+times+",个数："+i+",wcj+++"+map.strEPC);
            TagInfo info = new TagInfo();
            info.setBtAntId(map.btAntId);
            info.setMDate(map.mDate.toString());
            info.setNAnt1(map.nAnt1);
            info.setNAnt2(map.nAnt2);
            info.setNAnt3(map.nAnt3);
            info.setNAnt4(map.nAnt4);
            info.setNReadCount(map.nReadCount);
            info.setStrCRC(map.strCRC);
            info.setStrEPC(map.strEPC);
            info.setStrFreq(map.strFreq);
            info.setStrPC(map.strPC);
            info.setStrRSSI(map.strRSSI);
            tagInfoDao.insertOrReplace(info);
        }
    }

    /**
     * 得到标签数据
     * @return
     */
    public static InventoryBuffer getM_curInventoryBuffer(){
        if (null == m_curInventoryBuffer || null == m_curInventoryBuffer.lsTagList || m_curInventoryBuffer.lsTagList.size() <= 0){
            return null;
        }
        return m_curInventoryBuffer;
    }


    /**
     * 连接串口
     */
    public void connectPort(){
        mPosPort = mPortList.indexOf(TTYS1);
        if (DEBUG)
            Log.e(TAG, "test the value of mPosPort::" + mPosPort);
        if (mPosPort < 0) {
            Toast.makeText(activity,activity.getResources().getString(R.string.rs232_error),Toast.LENGTH_SHORT).show();
            return ;
        }
        try {
            mSerialPort = new SerialPort(new File(entryValues[mPosPort]), baud, 0);
            if (DEBUG)
                Log.e(TAG,"ttys1 value :::" + entryValues[mPosPort]);

            try {
                mReaderHelper = ReaderHelper.getDefaultHelper();
                mReaderHelper.setReader(mSerialPort.getInputStream(), mSerialPort.getOutputStream());//设置连接后的reader
            } catch (Exception e) {
                e.printStackTrace();

                return ;
            }
            if (!ModuleManager.newInstance().setUHFStatus(true)) {
                throw new RuntimeException("UHF RFID power on failure,may you open in other" +
                        " Process and do not exit it");
            }

//            Intent intent;
//            intent = new Intent().setClass(activity, ReadScanActivity.class);
//            activity.startActivity(intent);
            //finish();
        } catch (SecurityException e) {
            Toast.makeText(
                    activity,
                    activity.getResources().getString(R.string.error_security),
                    Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(
                    activity,
                    activity.getResources().getString(R.string.error_unknown),
                    Toast.LENGTH_SHORT).show();
        } catch (InvalidParameterException e) {
            Toast.makeText(
                    activity,
                    activity.getResources().getString(R.string.error_configuration),
                    Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 清除缓冲区里的数据
     */
    public void clearTagList(){
        if (null != m_curInventoryBuffer && null != m_curInventoryBuffer.lsTagList && m_curInventoryBuffer.lsTagList.size() > 0){
            m_curInventoryBuffer.clearInventoryRealResult();
        }
    }

    /**
     * 初始化在进行扫描的时候参数
     */
    private void initScanParam(){

        try {
            if (null == mReaderHelper)mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            return;
        }

        m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();

        lbm = LocalBroadcastManager.getInstance(activity);

        IntentFilter itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_ISO18000_6B);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_WRITE_DATA);

        lbm.registerReceiver(mRecv, itent);
    }

    private final BroadcastReceiver mRecv = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_ISO18000_6B)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);
                //mViewSetting.refreshReaderSetting(btCmd);
            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
                //mLogList.writeLog((String)intent.getStringExtra("log"), intent.getIntExtra("type", ERROR.SUCCESS));
            }
        }
    };

    public void setListener(OnTextChangeListener listener) {
        this.listener = listener;
    }

    private OnTextChangeListener listener;
    public interface OnTextChangeListener{
        void onChange(String text);
    }
}
